package com.sanqi.common.utils;

import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.function.Function;

public class SQMapUtil {
	public static <T, K> Map<T, K> ListToMap(Collection<K> list, Function<K, T> key){
		Map<T, K> map = new HashMap<>();
		if(list == null || list.isEmpty()) {
			return map;
		}
		for (K k : list) {
			T t = key.apply(k);
			map.put(t, k);
		}
		
		return map;
	}
	
	public static <T, K, R> Map<T, R> ListToMap(Collection<K> list, Function<K, T> key, Function<K, R> value){
		Map<T, R> map = new HashMap<>();
		if(list == null || list.isEmpty()) {
			return map;
		}
		for (K k : list) {
			T t = key.apply(k);
			R r = value.apply(k);
			map.put(t, r);
		}
		
		return map;
	}
	
	public static <T, K> Map<T, List<K>> ListToMapList(Collection<K> list, Function<K, T> key){
		Map<T, List<K>> map = new HashMap<>();
		if(list == null || list.isEmpty()) {
			return map;
		}
		for (K k : list) {
			T t = key.apply(k);
			List<K> value = map.get(t);
			if(null == value) {
				value = new ArrayList<>();
				value.add(k);
				map.put(t, value);
			} else {
				value.add(k);
			}
		}
		
		return map;
	}
	
	public static <T, K, R> Map<T, List<R>> ListToMapList(Collection<K> list, Function<K, T> key, Function<K, R> value){
		Map<T, List<R>> map = new HashMap<>();
		if(list == null || list.isEmpty()) {
			return map;
		}
		for (K k : list) {
			T t = key.apply(k);
			R r = value.apply(k);
			List<R> rList = map.get(t);
			if(null == rList) {
				rList = new ArrayList<>();
				rList.add(r);
				map.put(t, rList);
			} else {
				rList.add(r);
			}
		}
		
		return map;
	}
}
